//
//  SRCreateClassViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/7/20.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRCreateClassViewController.h"

#import <NSString+Enhanced.h>
#import "FCUtil.h"
#import "SRSchoolClassServices.h"
#import "SRValuePickerView.h"
#import "SRClassConstants.h"
#import <FZDirectionButton.h>

#import "SRAddToSchoolViewController.h"

@interface SRCreateClassViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *schoolNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *gradeTextField;
@property (weak, nonatomic) IBOutlet UITextField *classNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;

@property (strong, nonatomic) UIButton *rightButton;
@property (strong, nonatomic) SRValuePickerView *valuePickerView;//
@property (assign, nonatomic) NSInteger gradeInt;
@property (weak, nonatomic) IBOutlet FZDirectionButton *schoolButton;

@end

@implementation SRCreateClassViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"创建班级";
    
    [self setupView];
    
    [self setupNavigationItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:self.schoolNameTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:self.phoneTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:self.gradeTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:self.classNameTextField];

    WEAKSELF
    [self.view addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
        [weakSelf.view endEditing:YES];
    }];
    
    [self.schoolButton addTarget:self action:@selector(onSchoolButton:) forControlEvents:UIControlEventTouchUpInside];
    
    NSString *code = [SRLoginUser schoolID];
    if (code && [code integerValue] > 0) {
        self.schoolButton.hidden = YES;
    } else  {
        self.schoolButton.hidden = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)setupView {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    self.view.backgroundColor = css.color_2;
    
    self.schoolNameTextField.textColor = self.gradeTextField.textColor = self.classNameTextField.textColor = self.phoneTextField.textColor = [UIColor colorWithHex:0x29221c];
    self.schoolNameTextField.font = self.gradeTextField.font = self.classNameTextField.font = self.phoneTextField.font = css.fontOfH6;
    self.schoolNameTextField.delegate = self.phoneTextField.delegate= self.gradeTextField.delegate = self.classNameTextField.delegate = self;
    
    self.valuePickerView = [[SRValuePickerView alloc] init];
    
    self.schoolButton.layoutDirection = FZDirectionButtonLayoutHorizontalImageRight;
    [self.schoolButton setTitleColor:css.color_7 forState:UIControlStateNormal];
}


- (void)setupNavigationItem {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 40, 40);
    [rightButton setTitle:@"提交" forState:UIControlStateNormal];
    rightButton.titleLabel.font = css.fontOfH4;
    
    self.rightButton = rightButton;
    [rightButton addTarget:self action:@selector(onRightButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    [self setRightBarButtonItem:rightItem];
}


#pragma mark - Event

- (void)toChangeGrade {
    
    NSMutableArray *dataArray = [@[] mutableCopy];
    for (int i = 1; i <= 12; ++ i) {
        NSString *gradeString = [NSString stringWithFormat:@"%d年级", i];
        [dataArray addObject:gradeString];
    }
    
        //    self.pickItems = @[@"1年级", @"2年级", @"3年级", @"4年级", @"5年级", @"6年级", @"7年级", @"8年级", @"9年级", @"10年级", @"11年级", @"12年级"];
    
    self.valuePickerView.dataSource = dataArray;
    self.valuePickerView.pickerTitle = @"所在年级";
    WEAKSELF
    self.valuePickerView.valueDidSelectBlock = ^(NSString *value, NSInteger selectedRow){
        weakSelf.gradeTextField.text = value;
        
        weakSelf.gradeInt = selectedRow + 1;
        
    };
    
    [self.valuePickerView show];
}

- (IBAction)onSchoolButton:(id)sender{
    SRAddToSchoolViewController *vc = [[SRAddToSchoolViewController alloc] initWithNibName:@"SRAddToSchoolViewController" bundle:nil];
    vc.isFromAddClass = YES;
    
    WEAKSELF
    vc.didChangeUserTypeBlock = ^{
        
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)onRightButton:(id)sender {
    WEAKSELF
    [self hideKeyboard];
    
    NSString *schoolName = [self schoolName];
    if (!schoolName || [schoolName length] == 0) {
        [self showHUDErrorMessage:@"请输入学校名称"];
        return;
    }
    
    NSString *grade = [self grade];
    if (!grade || [grade length] == 0) {
        [self showHUDErrorMessage:@"请输入年级"];
        return;
    }
    
    NSString *className = [self className];
    if (!className || [className length] == 0) {
        [self showHUDErrorMessage:@"请输入班级名称"];
        return;
    }
    
    NSString *phone = [self phone];
    if (!phone || [phone length] == 0) {
        [self showHUDErrorMessage:@"请输入联系电话"];
        return;
    }
    
    [weakSelf startProgressHUD];
    
    NSString *gradeString = [NSString stringWithFormat:@"%ld", (long)self.gradeInt];
    
    [SRSchoolClassServices createClassWithSchoolName:schoolName grade:gradeString className:className phone:phone successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDHintWithText:@"创建成功"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kSRCreateClassDidSuccessNotification object:nil];
            
            [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:1];
        } else {
            [weakSelf showHUDHintWithText:message];
        }
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDError];
    }];
}

- (void)hideKeyboard {
    [self.schoolNameTextField resignFirstResponder];
    [self.phoneTextField resignFirstResponder];
    [self.gradeTextField resignFirstResponder];
    [self.classNameTextField resignFirstResponder];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    if (textField == self.gradeTextField) {
        [self toChangeGrade];
        [self hideKeyboard];
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.schoolNameTextField) {
        [self.gradeTextField becomeFirstResponder];
    }
    else if (textField == self.gradeTextField) {
        [self.classNameTextField becomeFirstResponder];
    }
    else if (textField == self.classNameTextField) {
        [self.phoneTextField becomeFirstResponder];
    }
    else {
        [self.phoneTextField resignFirstResponder];
        [self onRightButton:nil];
    }
    
    return YES;
}

- (NSString *)schoolName {
    return [self.schoolNameTextField.text stringToTrimWhiteSpace];
}

- (NSString *)phone {
    return [self.phoneTextField.text stringToTrimWhiteSpace];
}
- (NSString *)grade {
    return [self.gradeTextField.text stringToTrimWhiteSpace];
}

- (NSString *)className {
    return [self.classNameTextField.text stringToTrimWhiteSpace];
}

- (void)textViewDidChangeNotification:(NSNotification *)notification {
    if (notification.object) {
        [self termTextForTextfield:notification.object maxLength:50];
    }
}


- (void)termTextForTextfield:(UITextField *)textField maxLength:(NSInteger)maxLength {
        //    NSInteger maxLength = 20;
    NSArray *lengths = [FCUtil stringLengthWithString:textField.text maxLength:maxLength];
    if([[lengths objectAtIndex:0] integerValue] > maxLength){
        NSString * text = [textField.text substringToIndex:[[lengths objectAtIndex:1] integerValue]];
        if([NSThread isMainThread]){
            textField.text = text;
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                textField.text = text;
            });
        }
            //        [self showHUDErrorMessage:@"已超出字符限制"];
        NSString *message = [NSString stringWithFormat:@"最大允许 %ld 字符", (long)maxLength];
        [self showHUDErrorMessage:message];
        
//        if (self.showMessageBlock) {
//            self.showMessageBlock(message);
//        }
    }
}
@end
